<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('指标年度')" prop="indicatorYear">
            <DatePicker v-model="form.indicatorYear" type="year" value-format="yyyy" :disabled="disabled" :placeholder="$t('指标年度')" @change="indicatorYearChange" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('季度')" prop="quarter">
            <el-select v-model="form.quarter" filterable :disabled="disabled" :placeholder="$t('季度')">
              <el-option
                v-for="dict in quarterOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('录入人')" prop="entrant">
            <UserSelect v-model="form.entrant" :placeholder="$t('录入人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('录入日期')" prop="entryDate">
            <DatePicker v-model="form.entryDate" :placeholder="$t('录入日期')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('整改意见')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('整改意见')" show-word-limit :maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('指标明细') }}</span>
      </div>
      <el-table v-loading="detailsLoading" :data="form.dealOperationalIndicatorsDetailsList" border class="nowrapTable formTable">
        <el-table-column :label="$t('指标名称')" align="center" prop="indicatorName" show-overflow-tooltip />
        <el-table-column :label="$t('指标方向')" align="center" prop="indicatorDirection" :formatter="indicatorDirectionFormat" />
        <el-table-column :label="$t('目标值(万/百分比/个)')" align="center" prop="targetValue">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.targetValue) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('实际值(万/百分比/个)')" align="center" prop="actualValue">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('实际值') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealOperationalIndicatorsDetailsList.' + scope.$index + '.actualValue'" :rules="rules.actualValue">
              <money v-model="scope.row.actualValue" :placeholder="$t('实际值')" @change="actualValueChange($event, scope.$index)" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('完成情况(%)')" align="center" prop="completeStatus">
          <template slot-scope="scope">
            <span :style="getColorStyle(scope.row)">{{ scope.row.completeStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('是否达标')" align="center" prop="whetherStandard" :formatter="whetherStandardFormat" />
        <el-table-column :label="$t('备注')" align="center" prop="remark" show-overflow-tooltip />
      </el-table>
      <!-- 附件列表 -->
      <FileTable :list.sync="form.fileList" has-permi="deal:indicators" data-type="deal_operational_indicators" :business-id="autoBusinessId($route.query.id, form)" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <save-btn has-permi="deal:indicators" />
    </div>
  </div>
</template>

<script>
    import { saveDealOperationalIndicators, getDealOperationalIndicators, getIndicatorsMaintainByIndicatorYear, checkForIndicatorYearAndQuarterRepeated } from '@/api/deal/operational/indicators/dealOperationalIndicators'
    import { getByCompanyId } from '@/api/deal/operational/setting/dealIndicatorsSetting'

    export default {
        data() {
            return {
                // 季度字典
                quarterOptions: [],
                // 指标方向
                indicatorDirectionOptions: [],
                // 是否达标
                whetherStandardOptions: [],
                otherBtnHide: false,
                // 表单参数
                form: {},
                // 遮罩层
                loading: false,
              detailsLoading: false,
                // 表单校验
                rules: {
                  indicatorYear: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], quarter: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], entrant: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], entryDate: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], actualValue: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ] }
            }
        },
      computed: {
        disabled() {
          return !!this.form.id
        }
      },
        created() {
            this.getDicts('indicator_quarter').then(response => {
                this.quarterOptions = response.data
            })
            this.getDicts('indicator_direction').then(response => {
              this.indicatorDirectionOptions = response.data
            })
          this.getDicts('sys_yes_no').then(response => {
            this.whetherStandardOptions = response.data
          })
        },
        methods: {
            // 初始化数据
            init(data) {
              this.loading = true
                if (data != null && data.id !== undefined) {
                    getDealOperationalIndicators(data.id).then(response => {
                        this.form = response.data
                      this.loading = false
                    })
                } else {
                    this.reset()
                  this.loading = false
                }
            },
            // 指标方向字典翻译
            indicatorDirectionFormat(row) {
              return this.selectDictLabel(this.indicatorDirectionOptions, row.indicatorDirection)
            },
            // 是否达标字典翻译
            whetherStandardFormat(row) {
              return this.selectDictLabel(this.whetherStandardOptions, row.whetherStandard)
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                companyId: this.$route.query.companyId,
                indicatorYear: undefined,
                quarter: undefined,
                entrant: this.$store.state.user.userId,
                entryDate: new Date(),
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                dealOperationalIndicatorsDetailsList: [],
                fileList: []
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
              this.$refs['form'].validate(async valid => {
                if (valid) {
                  this.loading = true
                  if (!this.disabled) {
                    const params = {
                      companyId: this.$route.query.companyId,
                      indicatorYear: this.form.indicatorYear,
                      quarter: this.form.quarter
                    }
                    const flag = await checkForIndicatorYearAndQuarterRepeated(params)
                    if (flag) {
                      this.$message({
                        type: 'warning',
                        message: this.$t('当前选择的指标年度和季度的运营指标数据已存在于该项目中')
                      })
                      this.loading = false
                      return
                    }
                  }
                  saveDealOperationalIndicators(this.form).then(response => {
                    if (response.code === 200) {
                      this.msgSuccess(this.$t('保存成功'))
                      this.closeForm()
                    } else {
                      this.msgError(response.msg)
                    }
                    this.loading = false
                  }).catch(() => {
                    this.loading = false
                  })
                } else {
                  this.locationError(document)
                }
              })
           },
          // 指标年度change
          indicatorYearChange(val) {
              this.detailsLoading = true
            const param = {
              companyId: this.$route.query.companyId,
              indicatorYear: val
            }
            getIndicatorsMaintainByIndicatorYear(param).then(response => {
              if (response.data.length === 0) {
                getByCompanyId(this.$route.query.companyId).then(res => {
                  this.form.dealOperationalIndicatorsDetailsList = res.data
                  this.detailsLoading = false
                })
              } else {
                this.form.dealOperationalIndicatorsDetailsList = response.data
                this.detailsLoading = false
              }
            })
          },
          // 实际值change
          actualValueChange(val, index) {
            const row = this.form.dealOperationalIndicatorsDetailsList[index]
            if (val && row.targetValue) {
              if (row.indicatorDirection === 'Z') {
                row.completeStatus = (val / row.targetValue * 100).toFixed(2)
                row.whetherStandard = val >= row.targetValue ? 'Y' : 'N'
              } else {
                row.completeStatus = ((1 - (val - row.targetValue) / row.targetValue) * 100).toFixed(2)
                row.whetherStandard = row.targetValue > val ? 'Y' : 'N'
              }
            }
          },
          getColorStyle(row) {
            if (row.completeStatus >= 100) {
              return 'color:#73d13d'
            } else if (row.completeStatus >= 70) {
              return 'color:#ffc53d'
            } else if (row.completeStatus >= 50) {
              return 'color:#EA7154'
            } else {
              return 'color:#272D30'
            }
          }
        }
    }
</script>

<style scoped>

</style>
